<?php
/**
 * Created by PhpStorm.
 * User: locove
 * Date: 15-6-6
 * Time: 下午4:33
 */
class Controller_Lowstock extends Controller {
    public function action_index() {
        $d = date("Y-m-d H:i:s");
        echo '低于安全库存数据导入开始'.$d."\n";
        //判断ldt_skus是否有昨天的数据，有则清空
        $haveId = DB::select('id')->from('ldt_skus')
            ->where('source', '=', 100)->where('status', '=', 4)
            ->limit(1)->execute('newerp')->get('id', 0);

        if($haveId) {
            DB::delete('ldt_skus')->where('source', '=', 100)->where('status', '=', 4)->execute('newerp');
        }

        $haves = DB::select('sku')->from('ldt_skus')
            ->where('source', '=', 100)->where('status', '=', 3)
            ->execute('newerp')->as_array(NULL, 'sku');

        //获取所有的sku以及销量
        $sql = "SELECT `sku`,SUM(`daysale`) `daysale`
                FROM `sku_sales`
                WHERE `count_date`='".date('Y-m-d',$_SERVER['REQUEST_TIME']-86400)."'
                AND `daysale`>0
                GROUP BY `sku`";

        $daysales = DB::query(Database::SELECT,$sql)
            ->execute('newerp')
            ->as_array('sku','daysale');

        $skus = array_chunk(array_keys($daysales), 3000);

        $i = 0;
        $skuStocks = array();
        //获取所有的sku以及库存
        foreach($skus as $sku){
            $status = skusystemapi::getSkuAndStatus($sku);
            $sku_status = array();
            foreach($status as $st){
                $sku_status[$st['sku']] = $st['status_id'];
            }
            $sku = json_encode($sku);
            $stock = json_decode(newerpapi::getSkuUsableStockIncludeHold($sku), TRUE);
            foreach($stock as $_sku=>$s) {
                if(isset($daysales[$_sku])) {
                    if($s < $daysales[$_sku] * 3 && !in_array($_sku, $haves)) {
                        if(strpos('-', $_sku) || strpos('X', $_sku) || strpos('(', $_sku) || strpos('+', $_sku) || strpos('_', $_sku))continue;
                        $skuStocks[$i]['sku'] = $_sku;
                        $skuStocks[$i]['sale'] = $daysales[$_sku];
                        $skuStocks[$i]['status'] = isset($sku_status[$_sku])?$sku_status[$_sku]:1;
                        $i ++;
                    }
                }
            }

            if(!empty($skuStocks)) {
                $re = DB::insert("ldt_skus")->columns(array('sku', 'sale', 'add_time', 'onsale', 'source', 'status'));
                foreach($skuStocks as $s){
                    $re->values(array($s['sku'], $s['sale'], $d, $s['status'], 100, 3));
                }
                $re->execute('newerp');
            }

            sleep(20);
        }
        echo '低于安全库存数据导入成功'.date("Y-m-d H:i:s")."\n";
    }
}